package com.haitonghop.modules.truyentranh;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.haitonghop.R;
import com.haitonghop.controls.AdsViewControl;
import com.haitonghop.controls.DataCachedControl;
import com.haitonghop.main.AdsBussiness;
import com.haitonghop.network.APIRequestWorker;
import com.haitonghop.network.Request;
import com.haitonghop.network.RequestListener;
import com.haitonghop.requester.TruyenTranhRequester;
import com.haitonghop.utils.AppSettingParams;
import com.haitonghop.utils.Logger;

public class TruyenTranhChapterListActivity extends Activity implements OnScrollListener, RequestListener, OnItemClickListener {

	LinearLayout loadingPage = null;
	LinearLayout loadingError = null;

	LinearLayout mainContent = null;
	AdsViewControl prviewTamDiem = null;
	LinearLayout loadingMore = null;
	ListView imageListView = null;

	TruyenTranhChapterRenderAdapter chapterRenderAdapter = null;
	String idModules = "";
	String nameTitle = "";
	String avatarChapter = "";
	boolean isLoading = false;

	long requestId = -1;
	int MAX_COUNT = 20;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);

		Bundle extras = getIntent().getExtras();

		if (extras != null) {
			idModules = extras.getString("href");
			nameTitle = extras.getString("NAME");
			avatarChapter = extras.getString("AVATAR");
			Logger.logMe("id = " + idModules);
		}
		// Remove notification bar
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.truyentranh_chapter_list_act);
		init();

		TextView moduleName = (TextView) findViewById(R.id.moduleName);
		moduleName.setText(nameTitle);

		loadingPage = (LinearLayout) findViewById(R.id.loadingpagetamdiem);
		loadingError = (LinearLayout) findViewById(R.id.loadingError);
		loadingMore = (LinearLayout) findViewById(R.id.loadMore);
		loadingError.setVisibility(View.INVISIBLE);

		mainContent = (LinearLayout) findViewById(R.id.mainContent);

		prviewTamDiem = (AdsViewControl) findViewById(R.id.prviewTamDiem);
		imageListView = (ListView) findViewById(R.id.imageListView);

		TextView textView = (TextView) findViewById(R.id.titleActivity);
		textView.setText(nameTitle);

		ImageButton button = (ImageButton) findViewById(R.id.menu_button_right);
		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				Intent itent = new Intent(TruyenTranhChapterListActivity.this, TruyenTranhSearchActivity.class);
				startActivity(itent);
			}
		});

		Button back = (Button) findViewById(R.id.btnBackAcvitity);
		if (back != null) {
			back.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					requestId = -1;
					DataCachedControl.getInstance().clearCached(DataCachedControl.TRUYENTRANH_CATEGORY_CHAPTER_LIST);
					finish();
				}
			});
		}
	}

	void doAdsByServer() {
		AdsBussiness.getInstance().doGetAdsFromServer(this, prviewTamDiem);
	}

	@Override
	protected void onDestroy() {
		APIRequestWorker.getInstance().clearAllRequests();
		DataCachedControl.getInstance().clearCached(DataCachedControl.TRUYENTRANH_CATEGORY_CHAPTER_LIST);
		super.onDestroy();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			requestId = -1;
			DataCachedControl.getInstance().clearCached(DataCachedControl.TRUYENTRANH_CATEGORY_CHAPTER_LIST);
			finish();
			return true;
		}

		return super.onKeyDown(keyCode, event);
	}

	boolean isStart = true;

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		if (isStart) {
			isStart = false;
			onStartUp();
		}
		// if(chapterRenderAdapter != null){
		// chapterRenderAdapter.setBookMark(TruyenTranhSession.getAllBookMark(this));
		// }
	}

	int page = 1;
	boolean isPrevPageStackMode = false;

	private void onStartUp() {

		loadingPage.setVisibility(View.VISIBLE);

		loadingError.setVisibility(View.INVISIBLE);
		loadingMore.setVisibility(View.INVISIBLE);
		loadingError.setVisibility(View.INVISIBLE);
		mainContent.setVisibility(View.INVISIBLE);
		prviewTamDiem.setVisibility(View.INVISIBLE);
		imageListView.setVisibility(View.INVISIBLE);

		// ArrayList<TruyenTranhChapterData> cachedList =
		// (ArrayList<TruyenTranhChapterData>)
		// DataCachedControl.getInstance().getCached(DataCachedControl.TRUYENTRANH_CATEGORY_CHAPTER_LIST);
		// if (cachedList != null && !cachedList.isEmpty()) {
		// fillDatatoGridView(cachedList);
		// } else {

		if (!AppSettingParams.isRevertChapter) {
			TruyenTranhRequester requesterMorePage = TruyenTranhRequester.getComicInfo(idModules, new RequestListener() {

				@Override
				public void onRequestFailed(String errorMsg, Request request) {
					// TODO Auto-generated method stub
					String load = idModules + "page/" + page;
					TruyenTranhRequester requester = TruyenTranhRequester.getComic(load, TruyenTranhChapterListActivity.this);
					requestId = AppSettingParams.nextRequestId();
					requester.setRequestId(requestId);
					APIRequestWorker.getInstance().addAPIRequest(requester);
				}

				@Override
				public void onRequestComplete(Request request) {

					if (request instanceof TruyenTranhRequester) {
						TruyenTranhRequester r = (TruyenTranhRequester) request;
						try {
							if (r.getData() != null && r.getData().has("data")) {
								JSONObject data = r.getData().getJSONObject("data");
								JSONArray pages = data.has("page") ? data.getJSONArray("page") : null;
								if (pages != null) {
									page = pages.length();
									isPrevPageStackMode = true;
								}
							}

						} catch (Exception e) {

						}

						Log.i("page", "" + page);
						String load = idModules + "page/" + page;
						TruyenTranhRequester requester = TruyenTranhRequester.getComic(load, TruyenTranhChapterListActivity.this);
						requestId = AppSettingParams.nextRequestId();
						requester.setRequestId(requestId);
						APIRequestWorker.getInstance().addAPIRequest(requester);
					}

				}
			});

			requestId = AppSettingParams.nextRequestId();
			requesterMorePage.setRequestId(requestId);
			APIRequestWorker.getInstance().addAPIRequest(requesterMorePage);
		} else {
			isPrevPageStackMode = false;
			page = 1;
			String load = idModules + "page/" + page;
			TruyenTranhRequester requester = TruyenTranhRequester.getComic(load, TruyenTranhChapterListActivity.this);
			requestId = AppSettingParams.nextRequestId();
			requester.setRequestId(requestId);
			APIRequestWorker.getInstance().addAPIRequest(requester);
		}
	}

	// }

	void init() {
	}

	void fillDatatoGridView(final ArrayList<TruyenTranhChapterData> requestedDataList) {

		if (imageListView != null) {
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					DataCachedControl.getInstance().putCached(DataCachedControl.TRUYENTRANH_CATEGORY_CHAPTER_LIST, new ArrayList<TruyenTranhChapterData>(requestedDataList));
					if (chapterRenderAdapter == null) {
						chapterRenderAdapter = new TruyenTranhChapterRenderAdapter(TruyenTranhChapterListActivity.this, 1, 1, requestedDataList);
						imageListView.setAdapter(chapterRenderAdapter);
					} else {
						chapterRenderAdapter.setBlockList(requestedDataList);
						chapterRenderAdapter.notifyDataSetChanged();
					}

					if (chapterRenderAdapter != null) {
						chapterRenderAdapter.setBookMark(TruyenTranhSession.getAllBookMark(TruyenTranhChapterListActivity.this));
					}

					imageListView.setOnItemClickListener(TruyenTranhChapterListActivity.this);
					imageListView.setOnScrollListener(TruyenTranhChapterListActivity.this);

					loadingPage.setVisibility(View.GONE);
					loadingError.setVisibility(View.GONE);
					loadingMore.setVisibility(View.GONE);

					mainContent.setVisibility(View.VISIBLE);
					prviewTamDiem.setVisibility(View.VISIBLE);
					imageListView.setVisibility(View.VISIBLE);

					isLoading = false;

					doAdsByServer();
				}
			});

		}
	}

	@Override
	public void onRequestComplete(final Request request) {
		Logger.logMe("requestId = " + requestId);

		if (request instanceof TruyenTranhRequester) {
			TruyenTranhRequester r = (TruyenTranhRequester) request;

			ArrayList<TruyenTranhChapterData> requestedDataList = new ArrayList<TruyenTranhChapterData>();
			try {
				JSONObject jsonObject = r.getData();

				JSONArray jsonArray = jsonObject.getJSONArray("chapters");

				final int size = jsonArray.length();
				if (isPrevPageStackMode) {
					for (int i = 0; i < size; i++) {
						JSONObject datas = jsonArray.getJSONObject(i);
						TruyenTranhChapterData detailModuleData = new TruyenTranhChapterData(datas, avatarChapter);
						requestedDataList.add(detailModuleData);
					}
				} else {
					for (int i = size - 1; i >= 0; i--) {
						JSONObject datas = jsonArray.getJSONObject(i);
						TruyenTranhChapterData detailModuleData = new TruyenTranhChapterData(datas, avatarChapter);
						requestedDataList.add(detailModuleData);
					}
				}

			} catch (Exception e) {

			}

			fillDatatoGridView(requestedDataList);
		}
	}

	@Override
	public void onRequestFailed(String errorMsg, Request request) {
		if (request instanceof TruyenTranhRequester && requestId == request.getRequestId()) {
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					loadingPage.setVisibility(View.GONE);
					loadingError.setVisibility(View.VISIBLE);
					loadingMore.setVisibility(View.GONE);

					mainContent.setVisibility(View.GONE);
					prviewTamDiem.setVisibility(View.GONE);
					imageListView.setVisibility(View.GONE);

					isLoading = false;

					doAdsByServer();
				}
			});
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int index, long arg3) {
		if (chapterRenderAdapter != null) {
			TruyenTranhChapterData diemMetalData = chapterRenderAdapter.getItem(index);

			final String href = diemMetalData.getUrl();
			if (href != null && !"".equals(href)) {
				Intent intent = new Intent(getApplication(), TruyenTranhViewActivity.class);
				intent.putExtra("href", href);
				intent.putExtra("NAME", diemMetalData.getName());
				intent.putExtra("index", index);

				TruyenTranhSession.setCurrentChapter(diemMetalData);

				startActivity(intent);
			}
		}
	}

	RequestListener listenerLoadMore = new RequestListener() {

		@Override
		public void onRequestFailed(String errorMsg, Request request) {
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					if (loadingMore != null && loadingMore.getVisibility() != View.GONE)
						loadingMore.setVisibility(View.GONE);
				}
			});

		}

		@Override
		public void onRequestComplete(Request request) {
			if (request instanceof TruyenTranhRequester) {

				TruyenTranhRequester r = (TruyenTranhRequester) request;

				final ArrayList<TruyenTranhChapterData> requestedDataList = new ArrayList<TruyenTranhChapterData>();
				try {
					JSONObject jsonObject = r.getData();

					JSONArray jsonArray = jsonObject.getJSONArray("chapters");
					final int size = jsonArray.length();
					if (isPrevPageStackMode) {
						for (int i = 0; i < size; i++) {
							JSONObject datas = jsonArray.getJSONObject(i);
							TruyenTranhChapterData detailModuleData = new TruyenTranhChapterData(datas, avatarChapter);
							requestedDataList.add(detailModuleData);
						}
					} else {
						for (int i = size - 1; i >= 0; i--) {
							JSONObject datas = jsonArray.getJSONObject(i);
							TruyenTranhChapterData detailModuleData = new TruyenTranhChapterData(datas, avatarChapter);
							requestedDataList.add(detailModuleData);
						}
					}
				} catch (Exception e) {

				}
				Log.i("onRequestComplete", "1");
				if (imageListView != null) {
					runOnUiThread(new Runnable() {

						@Override
						public void run() {
							if (chapterRenderAdapter != null) {
								ArrayList<TruyenTranhChapterData> cachedList = (ArrayList<TruyenTranhChapterData>) DataCachedControl.getInstance().getCached(
										DataCachedControl.TRUYENTRANH_CATEGORY_CHAPTER_LIST);
								if (cachedList != null && requestedDataList != null) {

									final int size = requestedDataList.size();
									// if (isPrevPageStackMode) {
									for (int i = 0; i < size; i++) {
										cachedList.add(requestedDataList.get(i));
									}
									// } else {
									// for (int i = size - 1; i >= 0; i--) {
									// cachedList.add(requestedDataList.get(i));
									// }
									// }

								}
								chapterRenderAdapter.appendData(requestedDataList);
							}

							if (!requestedDataList.isEmpty())
								isLoading = false;

							if (loadingMore != null && loadingMore.getVisibility() != View.GONE)
								loadingMore.setVisibility(View.GONE);
						}
					});

				}
			}

		}
	};

	@Override
	public void onScroll(AbsListView arg0, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
		int lastInScreen = firstVisibleItem + visibleItemCount;
		if (!isLoading && chapterRenderAdapter != null && !chapterRenderAdapter.isEmpty() && (lastInScreen == totalItemCount) && (page < 100)) {
			if (loadingMore != null && loadingMore.getVisibility() != View.VISIBLE)
				loadingMore.setVisibility(View.VISIBLE);
			isLoading = true;

			if (isPrevPageStackMode) {
				if (page > 1) {
					page -= 1;
				} else {
					loadingMore.setVisibility(View.GONE);
					return;
				}
			} else {
				page += 1;
			}

			String load = idModules + "page/" + page;
			TruyenTranhRequester requester = TruyenTranhRequester.getComic(load, listenerLoadMore);
			APIRequestWorker.getInstance().addAPIRequest(requester);
		}
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		// TODO Auto-generated method stub

	}
}
